//
//  YWManagePatrolLineTableViewController.m
//  maintain
//
//  Created by Kyo on 16/10/12.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWManagePatrolLineTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "YWLoginTool.h"
#import "MJRefresh.h"

#import "YWBuilding.h"
#import "YWBuildingManager.h"

#import "YWKeepWatchMission.h"
#import "YWKeepWatchMissionManager.h"

#import "YWSelectBuildingTableViewController.h"
#import "YWShowPatrolLineTableViewController.h"
#import "YWCreatePatrolLineTableViewController.h"

@interface YWManagePatrolLineTableViewController ()<YWSelectBuildingTableViewControllerDelegate>{
    YWBuilding *currentBuilding;
}
@property (nonatomic, strong) NSArray *allPatrolLineOptions;
@end

@implementation YWManagePatrolLineTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"manageKeepWatchLine", nil);
    
    NSArray *allBuildings = [[YWBuildingManager shareManager] allBuilding];
    currentBuilding = allBuildings.count>0 ? allBuildings[0] : nil;
    
    [self setupNotifications];
    [self initTableView];
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshCreatePatrolLineNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshDeletePatrolLineNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshModifyPatrolLineNotification object:nil];
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0f;
    self.tableView.rowHeight = 44.0f;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}

- (void)refreshTop{
    YWWeakSelf(weakSelf);
    [[YWKeepWatchMissionManager shareManager] requestPatrolLineWithBuildingId:currentBuilding.buildingId Complete:^(NSArray *lineArray) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView.mj_header endRefreshing];
            if (lineArray.count > 0) {
                weakSelf.allPatrolLineOptions = lineArray;
                [weakSelf.tableView reloadData];
            }
        });
    }];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section==2 ? (self.allPatrolLineOptions.count ? self.allPatrolLineOptions.count : 1 ) : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"YWManagePatrolLineCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.textLabel.font = kContentFont;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section==0) {
        cell.textLabel.text = currentBuilding ? currentBuilding.buildingName : NSLocalizedString(@"none", nil);
    }else if (indexPath.section==1){
        cell.textLabel.text = NSLocalizedString(@"buildKeepWatchLine", nil);
    }else if (indexPath.section==2){
        if (self.allPatrolLineOptions.count) {
            YWPatrolLineOption *lineOption = self.allPatrolLineOptions[indexPath.row];
            cell.textLabel.text = lineOption.patrolLineName?:@"";
        }else{
            if (currentBuilding) {
                cell.textLabel.text = NSLocalizedString(@"noLine", nil);
            }else{
                NSString *buildingShowName = [YWLoginTool buildingShowName];
                NSString *title = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"firstSelect", nil),buildingShowName.length?buildingShowName:NSLocalizedString(@"building", nil)];
                cell.textLabel.text = title;
            }
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
        selectBuildingVC.delegate = self;
        selectBuildingVC.ownBuilding = currentBuilding;
        [self.navigationController pushViewController:selectBuildingVC animated:YES];
    }else if (indexPath.section==1){
        YWCreatePatrolLineTableViewController *createPatrolLineVC = [[YWCreatePatrolLineTableViewController alloc] init];
        createPatrolLineVC.buildingId = currentBuilding.buildingId;
        [self.navigationController pushViewController:createPatrolLineVC animated:YES];
    }else if (indexPath.section==2){
        YWPatrolLineOption *lineOption = self.allPatrolLineOptions[indexPath.row];
        YWShowPatrolLineTableViewController *showLineVC = [[YWShowPatrolLineTableViewController alloc] init];
        showLineVC.patrolLineOption = lineOption;
        [self.navigationController pushViewController:showLineVC animated:YES];
    }
}

#pragma mark - YWSelectBuildingTableViewControllerDelegate
-(void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![currentBuilding.buildingId isEqualToString:building.buildingId]) {
        currentBuilding = building;
        _allPatrolLineOptions = nil;
        [self refreshTop];
        [self.tableView reloadData];
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWManagePatrolLineForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section==0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        NSString *title = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"select", nil),buildingShowName.length?buildingShowName:NSLocalizedString(@"building", nil)];
        return title;
    }else if (section == 1) {
        return NSLocalizedString(@"newlyBuild", nil);//@"新建";
    }else if (section==2){
        return NSLocalizedString(@"allLine", nil);//@"所有路线";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
